package tcp;

import java.util.Arrays;

import com.serotonin.io.serial.SerialParameters;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.msg.ReadCoilsRequest;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;

public class tre_1 {
	public static String ipAdress;
	public static int ipPort; 
    public static int slaveId;
	public static int start;
	public static int len;
	public tre_1(String ipAdress1, int ipPort1, int slaveId1, int start1, int len1)
	{
		ipAdress = ipAdress1; 
		ipPort = ipPort1; 
		 slaveId = slaveId1;
		 start = start1;
		 len  = len1;
	};
	public static int[] remain1(){
		boolean[] result = null;
	    IpParameters ipParameters = new IpParameters();
        ipParameters.setHost(ipAdress);
        ipParameters.setPort(ipPort);
		ModbusFactory modbusFactory = new ModbusFactory();

		ModbusMaster master = modbusFactory.createTcpMaster(ipParameters, false);
        try {
			master.init();
		} catch (ModbusInitException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        result = readCoilTest(master, slaveId, start, len);
        //System.out.println(result[0]);
        int resultint[] = new int[result.length];
        for(int i=0; i<result.length; i++)
           {//System.out.println(result[i]);
     	  
     	   if(result[i]) 
     	   {
     		  resultint[i] = 1;  
     	   }
     	   else
     		  resultint[i] = 0;
     	  // System.out.println("1111");
     	   
     	  // System.out.println(resultint[i]);
     	   }

        master.destroy();
        return resultint;
	};

	   public static boolean[] readCoilTest(ModbusMaster master, int slaveId3, int start3, int len3) {
		   boolean[] result1 = null;
		   try {
	            ReadCoilsRequest request = new ReadCoilsRequest(slaveId3, start3, len3);
	            ReadCoilsResponse response = (ReadCoilsResponse) master.send(request);

	            if (response.isException())
	                System.out.println("Exception response: message=" + response.getExceptionMessage());
	            else
	                System.out.println(Arrays.toString(response.getBooleanData()));
	            	//System.out.println( response.getBooleanData());
	            result1 = response.getBooleanData();
		   }
	        catch (ModbusTransportException e) {
	            e.printStackTrace();
	        }
	        return result1;
	       // return Arrays.toString(response.getBooleanData());
	    }
}
